import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import numeral from 'numeral';
import * as compService from '../../../services/CompAccoEditInrt';
import COMP_ACCO_INRT_WHQK from './COMP_ACCO_INRT_WHQK'
const daoName = "DgckLLwh";
const ButtonGroup = Button.Group;
const renderNumber = (num) => {
    let value = ''
    if (num) {
        value = numeral(num).format('0,0.00')
    }
    return value
};
const columns = [
    { title: '账户', width: 260, sorter: true, key: 'ACNO', dataIndex: 'ACNO', dispaly: true, filter: true },
    { title: '子账户', width: 110, sorter: true, key: 'BANO', dataIndex: 'BANO', dispaly: true, filter: true },
    { title: '客户名称', width: 250, sorter: true, key: 'CUNM', dataIndex: 'CUNM', dispaly: true, filter: true },
    { title: '开户日期', width: 120, sorter: true, key: 'OPDT', caption: "OPDT", render: data => datetime.format(data.OPDT, "yyyy-MM-dd"), dispaly: true, filter: true, },
    { title: '科目', width: 150, sorter: true, key: 'ITNM', dataIndex: 'ITNM', dispaly: true, filter: true },
    { title: '维护利率', width: 120, sorter: true, key: 'INRT', render: data => data.INRT === 0 ? "" : data.INRT, dispaly: true, filter: true },
    { title: '当前余额', width: 120, sorter: true, key: 'ACBL', render: data => renderNumber(data.ACBL), dispaly: true, filter: true },
    { title: '起息日', width: 120, sorter: true, key: 'VLDT', caption: "VLDT", render: data => datetime.format(data.VLDT, "yyyy-MM-dd"), dispaly: true, filter: true, },
    { title: '到期日', width: 120, sorter: true, key: 'MODT', caption: "MODT", render: data => datetime.format(data.MADT, "yyyy-MM-dd"), dispaly: true, filter: true, },
];
const controls = [
    { name: 'ACNO', required: false, type: 'text', label: '账户', grid: 12 / 24, disabled: true },
    { name: 'BANO', required: false, type: 'text', label: '子账户', grid: 12 / 24, disabled: true },
    { name: 'CUNM', required: false, type: 'text', label: '客户名称', grid: 12 / 24, disabled: true },
    { name: "OPDT", required: false, type: "date", label: "开户日期", grid: 12 / 24, dataType: "date", disabled: true },
    { name: 'ITNM', required: false, type: 'text', label: '科目', grid: 12 / 24, disabled: true },
    { name: "VLDT", required: false, type: "date", label: "起息日", grid: 12 / 24, dataType: "date", disabled: true },
    { name: "MODT", required: false, type: "date", label: "到期日", grid: 12 / 24, dataType: "date", disabled: true },
    { name: 'ACBL', required: false, type: 'number', label: '当前余额', grid: 12 / 24, dataType: "number", disabled: true },
    { name: 'INRT', required: true, type: 'number', label: '维护利率(%)', grid: 12 / 24, dataType: "number", layout: { labelSpan: 8, wrapperSpan: 14 } },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class DgllwhForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let sort = {
            field: 'OPDT',
            order: 'descend'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要编辑的行！');
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的行！');
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}行数据吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    edidOkHandler() {
        let { jlid, inrt } = 0
        jlid = this.props.selectedRowKeys[0]
        const form = this.refs.DgllwhForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                controls.map((c, i) => {
                    values[c.name] = Number(values[c.name])
                })
            }
            inrt = values["INRT"]
        });
        compService.Edit({ jlid, inrt }
        ).then(function (data) {
            if (data) {
                message.success('数据修改成功！')
            } else {
                return;
            }
        }).catch(function (ex) {
            console.log('请求出错', ex)
        });
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, pageSize: 20 }
        });
    };
    hideEditHandler() {
        const form = this.refs.DgllwhForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    Add() {
        let { jlid, inrt } = 0
        let sxrq = ''
        const form = this.refs.editForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                if (values["ACNO"] === '') {
                    message.error("账户不能为空！")
                    return
                }
                if (values["SXRQ"] === null) {
                    message.error("生效日期不能为空！")
                    return
                }
                if (values["INRT"] === undefined) {
                    message.error("利率不能为空！")
                    return
                }
            }
            jlid = values["ACNO"]
            inrt = values["INRT"]
            sxrq = datetime.format(values["SXRQ"], "yyyy-MM-dd")
        });
        compService.Add({ jlid, inrt, sxrq }
        ).then(function (data) {
            if (data === "OK") {
                message.success('数据添加成功！')
            } else if (data === "NO") {
                message.error('该客户已维护，请在列表中维护！！！')
            }
        }).catch(function (ex) {
            console.log('请求出错', ex)
        });
        form.resetFields();
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, pageSize: 20 }
        });
    }
    render() {
        let { showEdit, record, permID, popedomTypes } = this.props
        const controlsEdit = [
            // {
            //     name: 'ACNO', type: 'search', label: '账户', grid: 13 / 24,
            //     fetch: { daoName: "COMP_ACCO_SC", searchColumns: ['NAME'], optionTpl: 'NAME', valueTpl: "ID" },
            //     layout: { labelSpan: 2, wrapperSpan: 21 }
            // },
            // { name: 'SXRQ', type: 'date', label: '生效日期', grid: 5 / 24, dataType: "date", layout: { labelSpan: 8, wrapperSpan: 13 } },
            // { name: 'INRT', type: 'number', label: '利率(%)', grid: 3 / 24, dataType: "number", layout: { labelSpan: 11, wrapperSpan: 10 } },
            { name: 'bg_1', type: 'button-group', data: [{ value: '2', label: '利率维护', onClick: this.showModelHandler.bind(this, false) }], grid: 3 / 24 }
        ]
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        <EditFrom ref="editForm" daoName={daoName} controls={controlsEdit} clearItemMargin={true} />
                    </div>
                    {/* <Modal title="编辑" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <EditFrom ref="DgllwhForm" daoName={daoName} controls={controls} record={record} />
                    </Modal> */}
                    <COMP_ACCO_INRT_WHQK ref="divi" jlid={record.ID} title={"【" + record.CUNM + "】 利率维护"} showEdit={showEdit} parentModel={daoName} />
                    <DataTable ref="BaseTcbzTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state.DgckLLwh
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record
    }
}
DgllwhForm = connect(mapStateToProps)(DgllwhForm)
export default DgllwhForm;

let render = (props) => React.createElement(DgllwhForm, props);
let f = new Factory()
f.set("DgllwhForm", render)
